//
//  RegistViewController.m
//  Fish
//
//  Created by KING on 16/4/20.
//  Copyright © 2016年 huwo. All rights reserved.
//

#import "RegistViewController.h"
#import "QuartzCore/QuartzCore.h"
#import "RegistTwoViewController.h"
#import "Header.h"
#import <SVProgressHUD.h>
@interface RegistViewController ()
@property (nonatomic, strong) UITextField *phoneText;
@property (nonatomic, strong) UITextField *passText;
@property (nonatomic, strong) UIButton *sendButton;
@property (nonatomic, strong) UITextField *passwordText;
@property (nonatomic, strong) UIButton *nextButton;
@property (nonatomic, strong) NSString *passWord;
@property (nonatomic, strong) UIWebView *webView;
@end

@implementation RegistViewController

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor = [UIColor colorWithRed:55/255.0 green:58/255.0 blue:62/255.0 alpha:1];
    self.view.backgroundColor = [UIColor whiteColor];
//    SVProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];

    
    
    // Do any additional setup after loading the view.
    
//    UILabel *la = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, kUIScreenWidth, 85)];
//    la.text = @"注册";
//    la.backgroundColor = [UIColor colorWithRed:55/255.0 green:58/255.0 blue:62/255.0 alpha:1];
//    la.textAlignment = NSTextAlignmentCenter;
//    la.textColor = [UIColor whiteColor];
//    [self.view addSubview:la];
//    
//    UIButton *leftButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    leftButton.frame = CGRectMake(20, 30, 30, 30);
//    [leftButton setImage:[UIImage imageNamed:@"nav_but_back"] forState:UIControlStateNormal];
//    [self.view addSubview:leftButton];
//    [leftButton addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    
   
    
    self.phoneText = [[UITextField alloc] initWithFrame:CGRectMake(kUIScreenWidth/2-140, 140, 280, 45)];
    [self.view addSubview:self.phoneText];
    self.phoneText.layer.borderColor=[[UIColor colorWithRed:106/255.0 green:107/255.0 blue:108/255.0 alpha:1] CGColor];
    self.phoneText.layer.borderWidth = 1.0;
    self.phoneText.placeholder = @"   |请填写手机号";
    self.phoneText.textColor = [UIColor colorWithRed:106/255.0 green:107/255.0 blue:108/255.0 alpha:1];
    [self.phoneText addTarget:self action:@selector(textValueChanged) forControlEvents:UIControlEventEditingChanged];
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 13, 21)];
    label.backgroundColor = [UIColor clearColor];
    self.phoneText.leftViewMode = UITextFieldViewModeAlways;
    self.phoneText.leftView = label;
    
    
    self.passText = [[UITextField alloc ]initWithFrame:CGRectMake(kUIScreenWidth/2-140, 200, 160, 45)];
    [self.view addSubview:self.passText];
    self.passText.layer.borderColor=[[UIColor colorWithRed:106/255.0 green:107/255.0 blue:108/255.0 alpha:1] CGColor];
    self.passText.layer.borderWidth = 1.0;
   
    
    UILabel *blabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 13, 21)];
    blabel.backgroundColor = [UIColor clearColor];
    self.passText.leftViewMode = UITextFieldViewModeAlways;
    self.passText.leftView = blabel;
    
    
    self.sendButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sendButton.frame  = CGRectMake(kUIScreenWidth/2+30, 200, 100, 45);
    [self.sendButton setTitle:@"发送验证码" forState:UIControlStateNormal];
//    [self.sendButton setTitleColor:[UIColor colorWithRed:45/255.0 green:135/255.0 blue:255/255.0 alpha:1] forState:UIControlStateNormal];
    [self.sendButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.view addSubview:self.sendButton];
//    self.sendButton.layer.borderColor = [[UIColor colorWithRed:45/255.0 green:135/255.0 blue:255/255.0 alpha:1]CGColor];
    self.sendButton.layer.borderColor = [[UIColor blackColor]CGColor];
    self.sendButton.layer.borderWidth = 1.0;
    [self.sendButton addTarget:self action:@selector(sendAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.passwordText = [[UITextField alloc] initWithFrame:CGRectMake(kUIScreenWidth/2-140, 260, 280, 45)];
    self.passwordText.placeholder = @"   |请设置密码";
    self.passwordText.textColor = [UIColor colorWithRed:106/255.0 green:107/255.0 blue:108/255.0 alpha:1];
    [self.view addSubview:self.passwordText];
    self.passwordText.layer.borderWidth = 1.0;
    self.passwordText.layer.borderColor = [[UIColor colorWithRed:106/255.0 green:107/255.0 blue:108/255.0 alpha:1]CGColor];
  
    
    UILabel *clabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 13, 21)];
    clabel.backgroundColor = [UIColor clearColor];
    self.passwordText.leftViewMode = UITextFieldViewModeAlways;
    self.passwordText.leftView = clabel;
    
    
    self.nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.nextButton.frame = CGRectMake(kUIScreenWidth/2-140, 320, 280, 45);
    self.nextButton.backgroundColor = [UIColor colorWithRed:166/255.0 green:168/255.0 blue:170/255.0 alpha:1];
    [self.nextButton setTitle:@"完成" forState:UIControlStateNormal];
    [self.view addSubview:self.nextButton];
    [self.nextButton addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    
//    [KeyboardToolBar registerKeyboardToolBar:self.phoneText];
//    [KeyboardToolBar registerKeyboardToolBar:self.passText];
//    [KeyboardToolBar registerKeyboardToolBar:self.passwordText];

    self.navigationItem.title = @"注册";
    
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"nav_but_back"] style:(UIBarButtonItemStyleDone) target:self action:@selector(backAction)];
    backItem.tintColor = [UIColor grayColor];
    self.navigationItem.leftBarButtonItem = backItem;
    
//    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 100, 70, 70)];
////    [_webView setCenter:self.view.center];
//    NSData *gif = [NSData dataWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"动态灰色" ofType:@"gif"]];
//    _webView.userInteractionEnabled = NO;
//    [_webView loadData:gif MIMEType:@"image/gif" textEncodingName:@"UTF-8" baseURL:nil];
//    _webView.backgroundColor = [UIColor clearColor];
//    _webView.opaque = NO;
//    [self.view addSubview:_webView];
}

- (void)backAction{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)repre{
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}
- (void)textValueChanged{
    if (self.phoneText.text.length != 0) {
        [self.nextButton setBackgroundImage:[UIImage imageNamed:@"main_btn_nextstep@2x"] forState:UIControlStateNormal];
    }

}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    _webView.alpha = 0;
    [self.phoneText resignFirstResponder];
    [self.passText resignFirstResponder];
    [self.passwordText resignFirstResponder];
}
-(void)backAction:(UIButton *)btn{
    [self dismissViewControllerAnimated:YES completion:^{
        
        
    }];
}
-(void)nextAction:(UIButton *)btn{
//    RegistTwoViewController *re = [[RegistTwoViewController alloc] init];
//    [self.navigationController pushViewController:re animated:YES];
    
//    registTwoViewController *teVC = [[registTwoViewController alloc]init];
//    teVC.myDelegate = self;
//    teVC.phone = self.phoneText.text;
//    teVC.pass = self.passwordText.text;
//    [self presentViewController:teVC animated:YES completion:^{
//        
//        
//    }];
//    if (self.phoneText.text.length == 0) {
//        [AppTools HUDAlert:self.view string:@"手机号不能为空"];
//    }
//
    
//    NSLog(@"--=--%@",url);
///    NSString *urlEncode = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSDictionary *dic = @{@"Tel":self.phoneText.text,@"Username":self.phoneText.text,@"Password":self.passwordText.text,@"Type":@"0"};
    [AppTools postURL:@"http://api03.m0571.com/WebJson.aspx?book=Register&" data:dic success:^(id result) {
        NSLog(@"===%@",result);
        NSArray *array = [NSArray arrayWithArray:result];
        NSMutableDictionary *dic = array[0];
        NSString *string =[dic objectForKey:@"describe"];
        
        if ([string isEqualToString:@"注册成功"]) {
            
            NSLog(@"---%@",string);
            //            [AppTools HUDAlert:self.view string:string];
            
            
        }
        
        else{
            NSLog(@"---%@",string);
            //            [AppTools HUDAlert:self.view string:string];
        }

        
    } error:^(NSError *error) {
        
        
    }];
//    NSString *url = [NSString stringWithFormat:@"http://api03.m0571.com/WebJson.aspx?book=Register&Tel=%@&Password=%@",self.phoneText.text,self.passwordText.text];
//    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
//    session.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//    session.responseSerializer = [AFJSONResponseSerializer serializer];
//    session.requestSerializer = [AFJSONRequestSerializer serializer];
//    [session.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
//    [session.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
//    [session GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
////
////        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"===%@",responseObject);
//        NSArray *array = [NSArray arrayWithArray:responseObject];
//        NSMutableDictionary *dic = array[0];
//        NSString *string =[dic objectForKey:@"describe"];
//        
//        if ([string isEqualToString:@"注册成功"]) {
//            
//            NSLog(@"---%@",string);
//            //            [AppTools HUDAlert:self.view string:string];
//            
//            
//        }
//        
//        else{
//            NSLog(@"---%@",string);
//            //            [AppTools HUDAlert:self.view string:string];
//        }
//
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"shibai");
//        
//    }];
    
}
-(void)sendAction:(UIButton *)btn{
    
//    NSString *pattern = @"[^0-9]";
//    NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
//    
//    NSArray *results = [regex matchesInString:self.phoneText.text options:0 range:NSMakeRange(0, self.phoneText.text.length)];
//    
//    if (results.count != 0) {
//        [AppTools HUDAlert:self.view string:@"手机号码格式错误"];
//        return;
//    }
//    if (self.phoneText.text.length != 11) {
//        [AppTools HUDAlert:self.view string:@"手机号码格式错误"];
//        return;
//    }
//    
//    
//    NSDictionary *dic = @{@"mobile": self.phoneText.text};
    
    //   http://fish.hu-wo.com/mobile/mobile_check/
    
//    AFHTTPSessionManager *Manager = [AFHTTPSessionManager manager];
//    Manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
//    [Manager POST:[NSString stringWithFormat:@"http://%@/mobile/mobile_check/",URLFISH] parameters:dic progress:^(NSProgress * _Nonnull uploadProgress) {
//        
//        
//    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSMutableDictionary *dic  = [NSMutableDictionary dictionaryWithDictionary:responseObject];
//        NSString *string = [dic objectForKey:@"msg"];
//        NSLog(@"%@",string);
//        
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        
//        [AppTools HUDAlert:self.view string:@"请求失败"];
//    }];
//    
//    [self openCountdown];

}

// 开启倒计时效果
-(void)openCountdown{
    
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [self.sendButton setTitle:@"重新发送" forState:UIControlStateNormal];
                self.sendButton.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [self.sendButton setTitle:[NSString stringWithFormat:@"已发送(%.2d)", seconds] forState:UIControlStateNormal];
                self.sendButton.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
